<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
            v-model="queryParams.patientName"
            placeholder="请输入患者姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="就诊卡号" prop="medicalCardNumber">
        <el-input
            v-model="queryParams.medicalCardNumber"
            placeholder="请输入就诊卡号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCardNumber">
        <el-input
            v-model="queryParams.idCardNumber"
            placeholder="请输入身份证号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input
            v-model="queryParams.phoneNumber"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室" prop="department">
        <el-input
            v-model="queryParams.department"
            placeholder="请输入科室"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检测费" prop="testingFee">
        <el-input
            v-model="queryParams.testingFee"
            placeholder="请输入检测费"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="就诊日志" prop="visitDate">
        <el-date-picker clearable
                        v-model="queryParams.visitDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择就诊日志">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="就诊时间" prop="waitingTime">
        <el-date-picker clearable
                        v-model="queryParams.waitingTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择就诊时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约时间" prop="appointmentTime">
        <el-date-picker clearable
                        v-model="queryParams.appointmentTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:visits:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:visits:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:visits:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:visits:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="visitsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="患者姓名" align="center" prop="patientName" />
      <el-table-column label="就诊卡号" align="center" prop="medicalCardNumber" />
      <el-table-column label="身份证号" align="center" prop="idCardNumber" />
      <el-table-column label="手机号" align="center" prop="phoneNumber" />
      <el-table-column label="科室" align="center" prop="department" />
      <el-table-column label="检测费" align="center" prop="testingFee" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="就诊日志" align="center" prop="visitDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.visitDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="就诊时间" align="center" prop="waitingTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.waitingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="appointmentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointmentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="() => handleUpdate(scope.row)" v-hasPermi="['system:visits:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="() => handleDelete(scope.row)" v-hasPermi="['system:visits:remove']">删除</el-button>
          <el-button link type="primary" icon="View" @click="() => handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改核酸预约检测对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="visitsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者姓名" prop="patientName">
          <el-select v-model="form.patientName" placeholder="请选择患者" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in patientsList" :key="index" :value="item.id"
                       :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="就诊卡号" prop="medicalCardNumber">
          <el-input v-model="form.medicalCardNumber" placeholder="请输入就诊卡号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNumber">
          <el-input v-model="form.idCardNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="科室" prop="department">
          <el-input v-model="form.department" placeholder="请输入科室"  />
        </el-form-item>
        <el-form-item label="检测费" prop="testingFee">
          <el-input v-model="form.testingFee" placeholder="请输入检测费" />
        </el-form-item>
        <el-form-item label="就诊日志" prop="visitDate">
          <el-date-picker clearable
                          v-model="form.visitDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择就诊日志">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="就诊时间" prop="waitingTime">
          <el-date-picker clearable
                          v-model="form.waitingTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择就诊时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker clearable
                          v-model="form.appointmentTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="(item, index) in statuslist"
                :key="index"
                :label="item.label"
            >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>

    <el-dialog title="就诊详情" v-model="detailOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="患者姓名">{{ detailData.patientName }}</el-descriptions-item>
        <el-descriptions-item label="就诊卡号">{{ detailData.medicalCardNumber }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ detailData.idCardNumber }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detailData.phoneNumber }}</el-descriptions-item>
        <el-descriptions-item label="科室">{{ detailData.department }}</el-descriptions-item>
        <el-descriptions-item label="检测费">{{ detailData.testingFee }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ detailData.status }}</el-descriptions-item>
        <el-descriptions-item label="就诊日志">{{ detailData.visitDate }}</el-descriptions-item>
        <el-descriptions-item label="就诊时间">{{ detailData.waitingTime }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ detailData.appointmentTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailOpen = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Visits">
import { listVisits, getVisits, delVisits, addVisits, updateVisits } from "@/api/system/visits"
import { listPatients,getPatients } from "@/api/system/patients.js"
import {watch} from "vue";
import log from "@/views/monitor/job/log.vue";

const { proxy } = getCurrentInstance()

const visitsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const detailOpen = ref(false)
const detailData = ref({})
const patientsList = ref([])
const statuslist = ref([
  {
    label: "待体检",
    value: "0"
  },
  {
    label: "已完成",
    value: "1"
  },
  {
    label: "已退款",
    value: "2"
  }
])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patientName: null,
    medicalCardNumber: null,
    idCardNumber: null,
    phoneNumber: null,
    department: null,
    testingFee: null,
    status: null,
    visitDate: null,
    waitingTime: null,
    appointmentTime: null
  },
  rules: {
    patientName: [
      { required: true, message: "患者姓名不能为空", trigger: "blur" }
    ],
    medicalCardNumber: [
      { required: true, message: "就诊卡号不能为空", trigger: "blur" }
    ],
    idCardNumber: [
      { required: true, message: "身份证号不能为空", trigger: "blur" }
    ],
    phoneNumber: [
      { required: true, message: "手机号不能为空", trigger: "blur" }
    ],
    department: [
      { required: true, message: "科室不能为空", trigger: "blur" }
    ],
    testingFee: [
      { required: true, message: "检测费不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    visitDate: [
      { required: true, message: "就诊日志不能为空", trigger: "blur" }
    ],
    waitingTime: [
      { required: true, message: "就诊时间不能为空", trigger: "blur" }
    ],
    appointmentTime: [
      { required: true, message: "预约时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

watch(() => form.value.patientName, async (newValue, oldValue) => {
  // 在这里执行你想要操作的
  if (newValue) {
    form.value.medicalCardNumber=(await getPatients(newValue)).data.cardNo
    form.value.idCardNumber=(await getPatients(newValue)).data.idCard
    form.value.phoneNumber=(await getPatients(newValue)).data.phone
  }
});

/** 查询核酸预约检测列表 */
function getList() {
  loading.value = true
  listVisits(queryParams.value).then(async response => {
    visitsList.value = response.rows
    console.log(visitsList.value)
    for (var i = 0; i < visitsList.value.length; i++) {
      visitsList.value[i].phoneNumber = (await getPatients(visitsList.value[i].patientName)).data.phone
      visitsList.value[i].idCardNumber = (await getPatients(visitsList.value[i].patientName)).data.idCard
      visitsList.value[i].medicalCardNumber = (await getPatients(visitsList.value[i].patientName)).data.cardNo
      visitsList.value[i].patientName = (await getPatients(visitsList.value[i].patientName)).data.name
    }
    total.value = response.total
    loading.value = false
  })
  listPatients().then( response => {
    patientsList.value = response.rows
    console.log(response.rows)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    patientName: null,
    medicalCardNumber: null,
    idCardNumber: null,
    phoneNumber: null,
    department: null,
    testingFee: null,
    status: null,
    visitDate: null,
    waitingTime: null,
    appointmentTime: null
  }
  proxy.resetForm("visitsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加核酸预约检测"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getVisits(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改核酸预约检测"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["visitsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateVisits(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addVisits(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除核酸预约检测编号为"' + _ids + '"的数据项？').then(function() {
    return delVisits(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/visits/export', {
    ...queryParams.value
  }, `visits_${new Date().getTime()}.xlsx`)
}

function handleDetail(row) {
  getVisits(row.id).then(response => {
    detailData.value = response.data
    detailOpen.value = true
  })
}

getList()
</script>
